<template>
  <div>
    <QuillEditor 
      ref="myQuillEditor" 
      theme="snow" 
      v-model:content="content" 
      :options="editorOptions"
      contentType="html" 
      @update:content="setValue"
    />
    <input 
      type="file" 
      hidden 
      accept=".jpg,.png" 
      ref="fileBtn" 
      @change="handleUpload" 
    />
  </div>
</template>

<script setup>
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { ref, watch, onMounted, nextTick } from 'vue'

const props = defineProps({
  value: String
})

const emit = defineEmits(['updateValue'])

const content = ref('')
const myQuillEditor = ref(null)
const fileBtn = ref(null)

// 添加对父组件传入值的监听
watch(() => props.value, (newVal) => {
  if (newVal && myQuillEditor.value && newVal !== content.value) {
    // 使用 nextTick 确保 DOM 更新完成
    nextTick(() => {
      if (myQuillEditor.value.getHTML() !== newVal) {
        myQuillEditor.value.setHTML(newVal)
      }
    })
  }
})

const editorOptions = {
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],
      [{'size': ['small', false, 'large', 'huge']}],
      [{'font': []}],
      [{'align': []}],
      [{'list': 'ordered'}, {'list': 'bullet'}],
      [{'indent': '-1'}, {'indent': '+1'}],
      [{'header': 1}, {'header': 2}],
      ['image'],
      [{'direction': 'rtl'}],
      [{'color': []}, {'background': []}]
    ]
  },
  placeholder: '请输入内容...'
}

const imgHandler = (state) => {
  if (state) {
    fileBtn.value.click()
  }
}

const setValue = () => {
  if (myQuillEditor.value) {
    const html = myQuillEditor.value.getHTML()
    if (html !== props.value) {
      emit('updateValue', html)
    }
  }
}

const handleUpload = (e) => {
  const files = e.target.files
  if (!files || files.length === 0) return
  
  const file = files[0]
  // 这里应该是您的上传逻辑
  console.log('上传文件:', file)
  
  // 上传成功后插入图片的示例：
  // if (myQuillEditor.value) {
  //   const quill = myQuillEditor.value.getQuill()
  //   const range = quill.getSelection()
  //   if (range) {
  //     quill.insertEmbed(range.index, 'image', '图片URL')
  //     quill.setSelection(range.index + 1)
  //   }
  // }
  
  // 重置文件输入以允许再次选择同一文件
  e.target.value = null
}

onMounted(() => {
  nextTick(() => {
    if (myQuillEditor.value) {
      const quill = myQuillEditor.value.getQuill()
      
      // 添加图片处理程序
      if (quill.getModule('toolbar')) {
        quill.getModule('toolbar').addHandler('image', imgHandler)
      }
      
      // 设置初始值（使用 nextTick 确保编辑器完全初始化）
      if (props.value) {
        myQuillEditor.value.setHTML(props.value)
      }
    }
  })
})
</script>

<style scoped lang="scss">
:deep(.ql-editor) {
  min-height: 180px;
}

:deep(.ql-formats) {
  height: 21px;
  line-height: 21px;
}
</style>